package com.cloud.admin.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.cloud.admin.common.core.domain.AjaxResult;
import com.cloud.admin.common.utils.StringUtils;
import com.cloud.admin.config.AliOssConfig;
import com.cloud.admin.config.Config;
import com.cloud.admin.model.entity.SysUser;
import com.cloud.admin.service.SysUserService;
import com.cloud.admin.shiro.security.ShiroUtils;
import com.cloud.admin.shiro.service.PasswordService;
import com.cloud.common.oss.AliOssRequest;
import com.cloud.common.oss.AliOssResponse;
import com.cloud.common.oss.AliUploadHelper;
import com.cloud.common.shiro.model.User;
//import com.google.gson.Gson;
//import com.qiniu.common.QiniuException;
//import com.qiniu.common.Zone;
//import com.qiniu.http.Response;
//import com.qiniu.storage.Configuration;
//import com.qiniu.storage.UploadManager;
//import com.qiniu.storage.model.DefaultPutRet;
//import com.qiniu.util.Auth;
import lombok.AllArgsConstructor;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.FileInputStream;

/**
 * Created on 2019/7/26.
 *
 * @author douhaichao
 */
@RestController
@AllArgsConstructor
@RequestMapping("system/user/profile")
public class ProfileController extends BaseController {

    private final String prefix = "system/user/profile/";
    private final SysUserService userService;
    private final PasswordService passwordService;
    private final AliOssConfig aliOssConfig;
    private final Config config;

    /**
     * 个人信息
     */
    @GetMapping()
    public ModelAndView profile() {
        User user = ShiroUtils.getSysUser();
        ModelAndView view = super.baseView("profile", prefix + "profile");
        user.setAvatar(config.getImgUrl() + (StrUtil.isEmpty(user.getAvatar()) ? config.getInitAvatar() : user.getAvatar()));
//        user.setAvatar(config.getImgUrl() + user.getAvatar());
        view.addObject("user", user);
        view.addObject("roleGroup", userService.selectUserRoleGroup(user.getUserId()));
        view.addObject("postGroup", userService.selectUserPostGroup(user.getUserId()));
        return view;
    }

    @GetMapping("/checkPassword")
    public boolean checkPassword(String password) {
        User user = ShiroUtils.getSysUser();
        if (passwordService.matches(user, password)) {
            return true;
        }
        return false;
    }

    @GetMapping("/resetPwd")
    public ModelAndView resetPwd(ModelMap mmap) {
        User user = ShiroUtils.getSysUser();
        ModelAndView view = super.baseView("profile", prefix + "resetPwd");
        view.addObject("user", userService.selectUserById(user.getUserId()));
        return view;
    }

    @PostMapping("/resetPwd")
    public AjaxResult resetPwd(String oldPassword, String newPassword) {
        User user = ShiroUtils.getSysUser();
        if (StringUtils.isNotEmpty(newPassword) && passwordService.matches(user, oldPassword)) {
            user.setSalt(ShiroUtils.randomSalt());
            user.setPassword(passwordService.encryptPassword(user.getLoginName(), newPassword, user.getSalt()));
            if (userService.resetUserPwd(user) > 0) {
                ShiroUtils.setSysUser(userService.selectUserById(user.getUserId()));
                return success();
            }
            return error();
        } else {
            return error("修改密码失败，旧密码错误");
        }
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit")
    public ModelAndView edit(ModelMap mmap) {
        User user = ShiroUtils.getSysUser();
        ModelAndView view = super.baseView("edit", prefix + "edit");
        view.addObject("user", userService.selectUserById(user.getUserId()));
        return view;
    }

    /**
     * 修改头像
     */
    @GetMapping("/avatar")
    public ModelAndView avatar(ModelMap mmap) {
        User user = ShiroUtils.getSysUser();
        ModelAndView view = super.baseView("avatar", prefix + "avatar");
        view.addObject("user", userService.selectUserById(user.getUserId()));
        return view;
    }

    /**
     * 修改用户
     */
    @PostMapping("/update")
    public AjaxResult update(SysUser user) {
        Long userId = ShiroUtils.getUserId();
        user.setUserId(userId);
        if (userService.updateById(user)) {
            User uTaget = userService.selectUserById(userId);
            ShiroUtils.setSysUser(uTaget);
            return success();
        }
        return error();
    }

    /**
     * 保存头像
     */
    @PostMapping("/updateAvatar")
    public AjaxResult updateAvatar(@RequestParam("avatarfile") MultipartFile file) {
        User currentUser = ShiroUtils.getSysUser();
        try {
            if (!file.isEmpty()) {
                String fileType = "main_head";
                String fileDir = fileType + "/" + UUID.randomUUID().toString() + ".jpg";
                FileInputStream inputStream = (FileInputStream) file.getInputStream();
                AliOssRequest aliOssRequest = new AliOssRequest();
                BeanUtil.copyProperties(aliOssConfig, aliOssRequest);

                AliUploadHelper aliUploadHelper = new AliUploadHelper(aliOssRequest);
                AliOssResponse aliOssResponse =
                        aliUploadHelper.uploadSimple(inputStream, fileDir);
//                String path = uploadQNImg(inputStream, fileDir);
                SysUser sysUser = new SysUser();
                sysUser.setUserId(currentUser.getUserId());
                sysUser.setAvatar(aliOssResponse.getPath());
                if (userService.updateById(sysUser)) {
                    ShiroUtils.setSysUser(userService.selectUserById(currentUser.getUserId()));
                    return success();
                }
            }
            return error();
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 将图片上传到七牛云
     */
//    private String uploadQNImg(FileInputStream file, String key) {
//        // 构造一个带指定Zone对象的配置类
//        Configuration cfg = new Configuration(Zone.zone1());
//        // 其他参数参考类注释
//        UploadManager uploadManager = new UploadManager(cfg);
//        // 生成上传凭证，然后准备上传
//
//        try {
//            Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
//            String upToken = auth.uploadToken(qiNiuConfig.getBucket());
//            try {
//                Response response = uploadManager.put(file, key, upToken, null, null);
//                // 解析上传成功的结果
//                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//
//                String returnPath = qiNiuConfig.getPath() + "/" + putRet.key;
//                return returnPath;
//            } catch (QiniuException ex) {
//                Response r = ex.response;
//                System.err.println(r.toString());
//                try {
//                    System.err.println(r.bodyString());
//                } catch (QiniuException ex2) {
//                    //ignore
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return "";
//    }
}
